package com.qf.web.controller;

import com.alibaba.fastjson.JSON;
import com.qf.domain.GoodsType;
import com.qf.service.GoodsTypeService;
import com.qf.service.impl.GoodsTypeServiceImpl;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/goodstypeservlet")
public class GoodsTypeServlet extends BaseServlet {

    public String goodstypelist(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");//设置编码
        response.setContentType("appliction/json;charset=UTF-8");
        ServletContext application = this .getServletContext();
        String goodsType =(String) application.getAttribute("goodsType");
        if (goodsType != null) {
            response.getWriter().write(goodsType);
            System.out.println("从application中获取了");
            return null;
        }
        //查询商品类型进行回写
        //创建业务对象
        GoodsTypeService goodsTypeService = new GoodsTypeServiceImpl();
        //调用方法
        List<GoodsType> goodsTypes= goodsTypeService.findByLevel(1);
        System.out.println("从数据库中获取");
        //把集合转成json字符串
        String json = JSON.toJSONString(goodsTypes);
        //回写 返回json字符串
        response.getWriter().write(json);
        //将json存入servletcontext中
        application.setAttribute("goodType",json);
        return null;
    }
}
